package org.jdesktop.swingx.table.model;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.swing.event.TableModelEvent;
import javax.swing.table.TableModel;

import org.jdesktop.swingx.table.model.calc.I_Calc;

public class CalcRowTableModelWapper extends AbstractAddRowTableModelWapper {

	Map<Integer,I_Calc> defCalc;
	
	public CalcRowTableModelWapper(TableModel t,Map<Integer,I_Calc> defCalc) {
		super(t, t.getRowCount());
		this.defCalc=defCalc;
		calc();
	}

	
	public CalcRowTableModelWapper(TableModel t, int column,I_Calc calc) {
		super(t, t.getRowCount());
		defCalc=new HashMap<Integer,I_Calc>();
		defCalc.put(column, calc);
		calc();
	}

	private void calc(){
		Iterator<I_Calc> it=defCalc.values().iterator();
		while(it.hasNext())
			it.next().resert();
		for(int i=0;i<t.getRowCount();i++)
			for(int j=0;j<t.getColumnCount();j++){
				int realNumber=getRealColumnNumber(j);
				if(realNumber==-1)
					continue;
				I_Calc calc=defCalc.get(realNumber);
				if(calc!=null)
					calc.push(getValueAt(i, j));
		    }
	}
	
	
	@Override
	public int getRowCount() {
		return t.getRowCount()==0?0:t.getRowCount()+1;
	}

	@Override
	public Object getRowValue(int columnIndex) {
		int realNumber=getRealColumnNumber(columnIndex);
		if(realNumber==-1)
			return null;
		I_Calc calc=defCalc.get(realNumber);
		if(calc!=null)
			return calc.getValue();
		return null;
	}


	@Override
	public void tableChanged(TableModelEvent e) {
		belowRowIndex=t.getRowCount();
		calc();
	}
}
